const Books = require('../model/Books');
const BooksTypes = require('../model/BooksTypes');
const sequelize = require('../config/database');
const Sequelize = require('sequelize');

const { Op } = require('sequelize');

let booksController = {};

booksController.getPage = async (req, res) => {
  // console.log(req.userInfo);
  let { page, pageSize } = req.query;
  page = parseInt(page) || 1;
  pageSize = parseInt(pageSize) || 6;
  Books.belongsTo(BooksTypes, {
    sourceKey: 'id',
    foreignKey: 'cate_id',
  });
  let { count, rows } = await Books.findAndCountAll({
    include: BooksTypes,
    offset: (page - 1) * pageSize,
    limit: pageSize,
  });
  // 查询总书籍
  sequelize
    .query('SELECT count(*) as total FROM Books', {
      type: Sequelize.QueryTypes.SELECT,
    })
    .then((data) => {
      let totalCount = data[0].total;
      res.json({ rows, count, totalCount });
    })
    .catch((err) => {
      console.error('查询失败:', err);
    });
};

booksController.delBook = async (req, res) => {
  let { id } = req.params;
  // 再把数据库的那条数据删除
  let data = await Books.destroy({ where: { id } });
  if (data) {
    res.json({ code: 20000, message: '删除成功' });
    return;
  }
  res.json({ code: 20001, message: '删除失败' });
};

booksController.search = async (req, res) => {
  let { text } = req.query;
  console.log(text);
  let data = await Books.findAll({
    where: {
      title: {
        [Op.like]: `%${text}%`,
      },
    },
  });
  res.json(data);
};
booksController.getAllType = booksController.getAllType = async (req, res) => {
  let data = await BooksTypes.findAll();
  res.json(data);
};
booksController.addBook = (req, res) => {
  console.log(req.body);
  let { title, content, cateId, picture } = req.body;
  console.log('cateId', cateId);
  cateId = cateId || 0;
  Books.create({
    title,
    content,
    cate_id: cateId,
    picture,
  })
    .then(async () => {
      //   delFun();
      res.json({ code: 20000, message: '添加成功' });
    })
    .catch(async () => {
      // 添加失败时也要做删除
      //   delFun();
      res.json({ code: 20001, message: '添加失败' });
    });
};

booksController.getOneBook = async (req, res) => {
  let { id } = req.query;
  await Books.findOne({ where: { id } })
    .then((data) => {
      res.json(data);
    })
    .catch(() => {});
};

booksController.editOneBook = async (req, res) => {
  let { id } = req.params;
  let { title, content, cateId, picture } = req.body;

  await Books.update(
    { title, content, cate_id: cateId, picture },
    { where: { id } }
  )
    .then(() => {
      //   delFun();
      res.json({ code: 20000, message: '编辑成功' });
    })
    .catch(async () => {
      //   delFun();
      res.json({ code: 20001, message: '编辑失败' });
    });
};

module.exports = booksController;
